package com.aos.erp.fs.storage.handler;

import com.aos.erp.common.utils.DateUtils;
import com.aos.erp.fs.enums.FileUriType;
import com.aos.erp.fs.model.SysFile;
import com.aos.erp.fs.storage.FileStorageHandler;
import com.aos.erp.fs.storage.StorageConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@RefreshScope
@Component
public class LocalStorageHandler implements FileStorageHandler {

    @Value("${uploadFolder:/}")
    private String uploadFolder = "";

    @Override
    public boolean save(SysFile sysFile, MultipartFile file, String type) {

        //本地存储
        String exName = getExName(file.getOriginalFilename());

        String fPath = makeFilePath(uploadFolder, sysFile.getAppId(), "erp", "n_" + DateUtils.getXXTimeString() + RandomStringUtils.randomNumeric(4) + exName);

        try {
            file.transferTo(new File(uploadFolder + fPath));

            sysFile.setUriType(FileUriType.local);
            sysFile.setUriSrc(fPath);

            return true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return false;
    }

    @Override
    public boolean canHandler(SysFile sysFile, MultipartFile file, String type) {
        return StorageConstants.LOCAL_STORAGE.equalsIgnoreCase(type);
    }


    private String makeFilePath(String basePath, String appId, String bizType, String fileName) {
        String path = getStoragePath(appId, bizType);

        File file = new File(basePath + path);
        if (!file.exists()) {
            file.mkdirs();
        }

        path = path + File.separator + fileName;
        return path;
    }

    public static String getExName(String name) {
        int i = name.lastIndexOf(".");
        if (i > 0) {
            return name.substring(i);
        }
        return "";
    }


}
